<?php
class categoryModel extends Model{
	private $tb = 'category';

	public function __construct(){
		parent::__construct($this->tb);
	}

	private function _valid( &$data ){
		if( empty($data['name']) || $data['pid']=="" || $data['pid']==NULL || $data['pid']=='undefined' ){
			return $this->error( lang( array('required_fields','required') ) );	
		}elseif( !valid_str_len($data['name'],15) ){
			return $this->error( lang( array('cat','name','len_error') ) );	
		}elseif( $this->get_cate("name=".$data['name']) ){
			return $this->error( lang( array('cat','exists') ) );	
		}
		return true;
	}

	public function get_cat($id=""){
		$id = intval($id);
		if( empty($id) ){
			$where = '1';
		}else{
			$where = "C.id=$id";
		}
		$sql = 'SELECT C.id,C.name,P.id as p_id ,P.name as p_name FROM '.$this->get_table('category').' C LEFT JOIN '.$this->get_table('category').' P ON P.id=C.pid WHERE '.$where;
		$this->query($sql);
		return $this->get();
	}

	public function get_children($pid){
		$pid = intval($pid);
		if( empty($pid) ) return false;
		$all = $this->get();
		$return = array();
		$in = array($pid);
		if( is_array($all) ){
			foreach($all as $v){
				if( in_array($v['pid'],$in) ){
					$return[] = $v;
					$in[] = $v['id'];
				}
			}
			return $return;
		}
		return false;
	}

	public function get_children_ids($pid){
		$pid = intval($pid);
		if( empty($pid) ) return false;
		$all = $this->field(array('id','pid'))->get();
		$in = array($pid);
		if( is_array($all) ){
			foreach($all as $v){
				if( in_array($v['pid'],$in) ){
					$in[] = $v['id'];
				}
			}
		}
		return $in;
	}

	public function add_cat($data){
		if( !$this->_valid($data) ){
			$this->error( $this->get_error() );
		}	
		return $this->value($data)->add();
	}

	public function edit_cat($id, $data){
		return $this->where("id=".intval($id))->value($data)->update();
	}
	
	public function del_cat( $id ){
		return $this->where("id=".intval($id))->del();
	}
}
